package io.mycat.eye.agent.service.zkConfig;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ZkConfigServiceFactoryConfig {
    
    @Value("${zookeeper.host:localhost}")
    private String host;
    
    @Value("${zookeeper.post:2181}")
    private String port;
    
    @Bean
    public ZkConfigServiceFactory zkConfigServiceFactory() {
        int sessionTimeoutMs = 5000;
        //ExponentialBackoffRetry:重试指定的次数, 且每一次重试之间停顿的时间逐渐增加.
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
        CuratorFramework client = CuratorFrameworkFactory.builder()
                .connectString(host + ":" + port)
                .sessionTimeoutMs(sessionTimeoutMs)
                .retryPolicy(retryPolicy)
                .build();
        client.start();
        return new ZkConfigServiceFactory(client);
    }
    
    public class ZkConfigServiceFactory {
        
        CuratorFramework client;
        
        public ZkConfigServiceFactory(CuratorFramework c) {
            client = c;
        }

        public ZkConfigService create(String k, String path) {
            return new ZkConfigService(k, path, client);
        }

        public CuratorFramework getClient() {
            return client;
        }

        public void setClient(CuratorFramework client) {
            this.client = client;
        }
        
    }

}
